package com.zelin.homeworkAdd.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP通信-服务端
 * 单人聊天机器人
 */
public class TcpServerRobot {
    public static void main(String[] args) {

        ServerSocket server = null;
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //创建ServerSocket对象,创建服务端
            server = new ServerSocket(1014);
            System.out.println("服务器已开启...");
            //获得客户端Socket对象,等待客户端连接
            socket = server.accept();
            //获得客户端的输入请求,创建字节输入流
            inputStream = socket.getInputStream();
            //创建字节数组用于存储流里的信息
            byte[] b = new byte[1024];
            //判断信息并返回消息
            outputStream = socket.getOutputStream();

            while (true) {
                //把信息读入字节数组
                int length = inputStream.read(b);
                //将数组信息转为字符串
                String s = new String(b,0,length);

                String info;
                if (s.contains("你好")) {
                    info = "雷猴啊";
                } else if (s.contains("贵姓")) {
                    info = "不告诉你";
                } else if (s.contains("再见")) {
                    info = "拜拜";
                    outputStream.write(info.getBytes());
                    //结束聊天
                    return;
                } else {
                    info = "对不起,我听不懂你说什么,请换种方式问我";
                }
                //输出回复内容给客户端
                outputStream.write(info.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                assert outputStream != null;
                outputStream.flush();
                outputStream.close();
                inputStream.close();
                socket.close();
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
